package com.kedou.sdk.download;

import com.kedou.sdk.core.HttpEngineApi;
import com.kedou.sdk.core.HttpEngineConduits;
import com.kedou.sdk.utils.CommonUtils;
import com.kedou.sdk.utils.ResUtils;
import com.kedou.sdk.utils.ToolsUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public final class VersionUpdateDownloader extends BaseDownloader {

    private static final String CACHE_DIR = "/version/";

    private static VersionUpdateDownloader instance;

    private VersionUpdateDownloader() {
        super();
    }

    public static VersionUpdateDownloader getImpl() {
        synchronized (VersionUpdateDownloader.class) {
            if (instance == null) {
                instance = new VersionUpdateDownloader();
            }
        }
        return instance;
    }

    @Override
    public File getExternalDownloadDir() {
        File parent = super.getExternalDownloadDir();
        return new File(parent, CACHE_DIR);
    }

    @Override
    public File getDownloadApkVersionFile() {
        File downloadDir = getExternalDownloadDir();

        if (downloadDir.exists()) {
            File[] childFiles = downloadDir.listFiles();
            if (childFiles != null && childFiles.length > 0) {
                for (File child : childFiles) {
                    if (child.isFile()) {
                        String filename = child.getName();
                        if (filename.endsWith(".apk") && filename.startsWith("download_")) {
                            return child;
                        }
                    }
                }
            }
        }

        return null;
    }

    public int getDownloadedVersionCode() {
        int versionCode = 0;

        File downloadApk = getDownloadApkVersionFile();
        if (downloadApk != null && downloadApk.exists()) {
            String[] filenameSplit = downloadApk.getName().split("_");
            String versionCodeStr = filenameSplit.length >= 2 ? filenameSplit[1] : "";
            if (ToolsUtils.isNumberType(versionCodeStr)) {
                versionCode = Integer.parseInt(versionCodeStr);
            }
        }

        return versionCode;
    }

    @Override
    public File randomMakeDownloadStorageFile(String extension) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);

        StringBuilder builder = new StringBuilder("download_");
        builder.append(extension).append("_");
        builder.append(sdf.format(new Date()));
        builder.append(".apk");
        return new File(getExternalDownloadDir(), builder.toString());
    }

    public boolean isDownloading() {
        HttpEngineConduits conduits = HttpEngineApi.getInstance().getEngineConduits();
        final long downloadId = conduits.readVersionDownloadId();
        return super.isDownloading(downloadId);
    }

    public boolean checkDownloadFileCompletedStatus() {
        HttpEngineConduits conduits = HttpEngineApi.getInstance().getEngineConduits();
        final long downloadId = conduits.readVersionDownloadId();
        return super.checkDownloadFileCompletedStatus(downloadId);
    }

    public long startVersionDownloadTask(String downloadUrl, File storageFile, boolean notificationVisible) {
        long downloadId = 0;

        if (CommonUtils.existsDownloadedVersion()) {
            HttpEngineConduits conduits = HttpEngineApi.getInstance().getEngineConduits();
            downloadId = conduits.readVersionDownloadId();
            onDownloadCompleted(downloadId, getDownloadApkVersionFile());
            return downloadId;
        }

        String title = ToolsUtils.getAppName(getApplicationContext());
        String description = ResUtils.getString(getApplicationContext(), "hnssn_version_update_downloading");
        downloadId = super.startVersionDownloadTask(downloadUrl, storageFile, title, description, notificationVisible);

        HttpEngineConduits conduits = HttpEngineApi.getInstance().getEngineConduits();
        conduits.writeVersionDownloadId(downloadId);
        return downloadId;
    }

}
